﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Orange.Logistics.Models;
using Orange.Logistics.Services;

namespace Orange.Logistics.Infrastructure {
    /// <summary>
    /// Set Context before action result excution.
    /// </summary>
    public class PermissionAttribute : ActionFilterAttribute {
        private readonly IPermissionService serivce = new PermissionService();

        public override void OnActionExecuting(ActionExecutingContext filterContext) {
            System.Diagnostics.Debug.Assert(filterContext != null);

            if (!this.AuthorizeCore(filterContext)) {
                if (filterContext.IsChildAction) {
                    filterContext.Result = new EmptyResult();
                } else {
                    filterContext.Result = new RedirectResult("~/Error.htm");
                }
            }
        }

        protected virtual bool AuthorizeCore(ActionExecutingContext filterContext) {
            if (filterContext.HttpContext == null) {
                throw new ArgumentNullException("httpContext");
            }

            //Check If Anonymouse -> true
            if (filterContext.ActionDescriptor.GetCustomAttributes(
                        typeof(AnonymousAttribute), false).Count() > 0) {
                return true;
            }

            //If No Userinfo Session -> false
            UserInfo userinfo = filterContext.HttpContext.Session["CurrentUserInfo"] as UserInfo;
            if (userinfo == null) {
                return false;
            }

            var controller = filterContext.RouteData.Values["controller"].ToString();
            var action = filterContext.RouteData.Values["action"].ToString();

            // Check Right for specified Url
            return serivce.CheckRight(userinfo.RoleIDs, controller, action);
        }
    }
}